import logging
from logging.handlers import RotatingFileHandler
from singleton import SingletonBase

class AppLogger(SingletonBase):
    def __init__(self, log_file, slevel=logging.INFO,flevel=logging.INFO, max_bytes=1024*20, backup_count=1):
        # 创建一个logger
        self.logger = logging.getLogger('my_logger')
        self.logger.setLevel(slevel)
        
        # 判断logger是否已经添加了handlers，如果没有，才添加
        if not self.logger.handlers:
            # 创建一个RotatingFileHandler，最多备份3个日志文件，每个日志文件最大1024字节
            handler = RotatingFileHandler(log_file, maxBytes=max_bytes, backupCount=backup_count,encoding='utf-8')
            handler.setLevel(flevel)
            
            # 创建一个formatter，并添加到handler上
            formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
            handler.setFormatter(formatter)
            
            # 给logger添加handler
            self.logger.addHandler(handler)

    def info(self, message):
        self.logger.info(message)

    def error(self, message):
        self.logger.error(message)

    def disable_logging(self):
        """移除所有日志处理器，停止日志记录"""
        for handler in self.logger.handlers:
            handler.close()
            self.logger.removeHandler(handler)

if __name__=='__main__':
    # 使用示例
    logger = AppLogger('my_app.log', max_bytes=1024, backup_count=2)

    logger.info('This is an info message.')
    logger.error('This is an error message.')
    
    # 当需要停止日志记录时，调用disable_logging方法
    logger.disable_logging()
    logger.info('This is an info message.')
    logger.error('This is an error message.')
    
    